<template>
  <div class="disk-container">
    <!-- 顶部工具栏 -->
    <div class="toolbar">
      <div class="toolbar-left">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item @click="navigateToFolder(null)">我的网盘</el-breadcrumb-item>
          <el-breadcrumb-item 
            v-for="folder in breadcrumbs"
            :key="folder.id"
            @click="navigateToFolder(folder.id)"
          >
            {{ folder.name }}
          </el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <div class="toolbar-right">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索文件..."
          style="width: 200px; margin-right: 12px;"
          @keyup.enter="handleSearch"
        >
          <template #append>
            <el-button icon="Search" @click="handleSearch" />
          </template>
        </el-input>
        <el-button type="primary" @click="showUploadDialog = true">
          <el-icon><Upload /></el-icon>
          上传文件
        </el-button>
        <el-button @click="showCreateFolderDialog = true">
          <el-icon><FolderAdd /></el-icon>
          新建文件夹
        </el-button>
      </div>
    </div>

    <!-- 存储空间信息 -->
    <div class="storage-info">
      <el-progress 
        :percentage="storagePercentage" 
        :stroke-width="6"
        :show-text="false"
      />
      <span class="storage-text">
        已使用 {{ formatFileSize(storageInfo.used) }} / {{ formatFileSize(storageInfo.total) }}
      </span>
    </div>

    <!-- 文件列表 -->
    <div class="file-list">
      <!-- 列表头部 -->
      <div class="list-header">
        <el-checkbox 
          v-model="selectAll" 
          @change="handleSelectAll"
          :indeterminate="isIndeterminate"
        />
        <span class="header-item name">名称</span>
        <span class="header-item size">大小</span>
        <span class="header-item type">类型</span>
        <span class="header-item time">修改时间</span>
        <span class="header-item actions">操作</span>
      </div>

      <!-- 文件项 -->
      <div 
        v-for="item in fileList"
        :key="item.id"
        class="file-item"
        :class="{ selected: selectedFiles.includes(item.id) }"
        @click="handleItemClick(item)"
        @dblclick="handleItemDoubleClick(item)"
      >
        <el-checkbox 
          :model-value="selectedFiles.includes(item.id)"
          @change="handleItemSelect(item.id, $event)"
          @click.stop
        />
        <div class="file-info">
          <el-icon class="file-icon" :size="24">
            <component :is="getFileIcon(item)" />
          </el-icon>
          <span class="file-name">{{ item.name }}</span>
        </div>
        <span class="file-size">{{ item.type === 'folder' ? '-' : formatFileSize(item.size) }}</span>
        <span class="file-type">{{ getFileType(item) }}</span>
        <span class="file-time">{{ formatTime(item.updateTime) }}</span>
        <div class="file-actions" @click.stop>
          <el-dropdown @command="(command) => handleCommand(command, item)">
            <el-button type="text" size="small">
              <el-icon><MoreFilled /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="download" v-if="item.type !== 'folder'">
                  <el-icon><Download /></el-icon>下载
                </el-dropdown-item>
                <el-dropdown-item command="share">
                  <el-icon><Share /></el-icon>分享
                </el-dropdown-item>
                <el-dropdown-item command="rename">
                  <el-icon><Edit /></el-icon>重命名
                </el-dropdown-item>
                <el-dropdown-item command="move">
                  <el-icon><FolderOpened /></el-icon>移动
                </el-dropdown-item>
                <el-dropdown-item command="copy">
                  <el-icon><CopyDocument /></el-icon>复制
                </el-dropdown-item>
                <el-dropdown-item command="delete" divided>
                  <el-icon><Delete /></el-icon>删除
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>
    </div>

    <!-- 批量操作栏 -->
    <div v-if="selectedFiles.length > 0" class="batch-actions">
      <span>已选择 {{ selectedFiles.length }} 个文件</span>
      <el-button @click="batchDownload">批量下载</el-button>
      <el-button @click="batchMove">批量移动</el-button>
      <el-button @click="batchDelete" type="danger">批量删除</el-button>
    </div>

    <!-- 上传对话框 -->
    <el-dialog v-model="showUploadDialog" title="上传文件" width="600px">
      <el-upload
        ref="uploadRef"
        class="upload-demo"
        drag
        multiple
        :auto-upload="false"
        :on-change="handleFileChange"
        :file-list="uploadFileList"
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          将文件拖到此处，或<em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            支持多文件上传，单个文件不超过100MB
          </div>
        </template>
      </el-upload>
      <template #footer>
        <el-button @click="showUploadDialog = false">取消</el-button>
        <el-button type="primary" @click="handleUpload" :loading="uploading">
          开始上传
        </el-button>
      </template>
    </el-dialog>

    <!-- 新建文件夹对话框 -->
    <el-dialog v-model="showCreateFolderDialog" title="新建文件夹" width="400px">
      <el-form :model="folderForm" :rules="folderRules" ref="folderFormRef">
        <el-form-item label="文件夹名称" prop="name">
          <el-input v-model="folderForm.name" placeholder="请输入文件夹名称" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showCreateFolderDialog = false">取消</el-button>
        <el-button type="primary" @click="handleCreateFolder">确定</el-button>
      </template>
    </el-dialog>

    <!-- 重命名对话框 -->
    <el-dialog v-model="showRenameDialog" title="重命名" width="400px">
      <el-form :model="renameForm" :rules="renameRules" ref="renameFormRef">
        <el-form-item label="新名称" prop="name">
          <el-input v-model="renameForm.name" placeholder="请输入新名称" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showRenameDialog = false">取消</el-button>
        <el-button type="primary" @click="handleRename">确定</el-button>
      </template>
    </el-dialog>

    <!-- 分享对话框 -->
    <el-dialog v-model="showShareDialog" title="分享文件" width="500px">
      <el-form :model="shareForm" ref="shareFormRef">
        <el-form-item label="分享链接">
          <el-input v-model="shareLink" readonly>
            <template #append>
              <el-button @click="copyShareLink">复制</el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="提取码">
          <el-input v-model="shareForm.password" placeholder="可选，留空则无需提取码" />
        </el-form-item>
        <el-form-item label="有效期">
          <el-select v-model="shareForm.expireDays" placeholder="请选择有效期">
            <el-option label="1天" :value="1" />
            <el-option label="7天" :value="7" />
            <el-option label="30天" :value="30" />
            <el-option label="永久" :value="0" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showShareDialog = false">取消</el-button>
        <el-button type="primary" @click="handleShare">创建分享</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getFileList,
  getFolderContent,
  uploadFile,
  downloadFile,
  createFolder,
  renameFile,
  renameFolder,
  deleteFile,
  deleteFolder,
  createShare,
  getStorageInfo
} from '@/api/disk'

// 响应式数据
const currentFolderId = ref(null)
const breadcrumbs = ref([])
const fileList = ref([])
const selectedFiles = ref([])
const searchKeyword = ref('')
const storageInfo = ref({ used: 0, total: 0 })

// 对话框状态
const showUploadDialog = ref(false)
const showCreateFolderDialog = ref(false)
const showRenameDialog = ref(false)
const showShareDialog = ref(false)

// 上传相关
const uploadFileList = ref([])
const uploading = ref(false)

// 表单数据
const folderForm = reactive({ name: '' })
const renameForm = reactive({ name: '', id: null, type: null })
const shareForm = reactive({ password: '', expireDays: 7 })
const shareLink = ref('')

// 表单校验规则
const folderRules = {
  name: [{ required: true, message: '请输入文件夹名称', trigger: 'blur' }]
}
const renameRules = {
  name: [{ required: true, message: '请输入新名称', trigger: 'blur' }]
}

// 计算属性
const selectAll = computed({
  get: () => selectedFiles.value.length === fileList.value.length && fileList.value.length > 0,
  set: (val) => {
    if (val) {
      selectedFiles.value = fileList.value.map(item => item.id)
    } else {
      selectedFiles.value = []
    }
  }
})

const isIndeterminate = computed(() => {
  return selectedFiles.value.length > 0 && selectedFiles.value.length < fileList.value.length
})

const storagePercentage = computed(() => {
  if (storageInfo.value.total === 0) return 0
  return Math.round((storageInfo.value.used / storageInfo.value.total) * 100)
})

// 获取文件列表
const loadFileList = async () => {
  try {
    let response
    if (currentFolderId.value) {
      response = await getFolderContent(currentFolderId.value)
    } else {
      response = await getFileList()
    }
    
    if (response.code === 200) {
      fileList.value = response.data.files || []
    }
  } catch (error) {
    console.error('获取文件列表失败:', error)
    ElMessage.error('获取文件列表失败')
  }
}

// 获取存储信息
const loadStorageInfo = async () => {
  try {
    const response = await getStorageInfo()
    if (response.code === 200) {
      storageInfo.value = response.data
    }
  } catch (error) {
    console.error('获取存储信息失败:', error)
  }
}

// 导航到文件夹
const navigateToFolder = (folderId) => {
  currentFolderId.value = folderId
  selectedFiles.value = []
  loadFileList()
  // 更新面包屑导航
  // 这里需要根据实际情况更新breadcrumbs
}

// 处理文件选择
const handleItemSelect = (fileId, checked) => {
  if (checked) {
    selectedFiles.value.push(fileId)
  } else {
    const index = selectedFiles.value.indexOf(fileId)
    if (index > -1) {
      selectedFiles.value.splice(index, 1)
    }
  }
}

// 全选/取消全选
const handleSelectAll = (checked) => {
  if (checked) {
    selectedFiles.value = fileList.value.map(item => item.id)
  } else {
    selectedFiles.value = []
  }
}

// 处理项目点击
const handleItemClick = (item) => {
  // 单击选择/取消选择
  const index = selectedFiles.value.indexOf(item.id)
  if (index > -1) {
    selectedFiles.value.splice(index, 1)
  } else {
    selectedFiles.value.push(item.id)
  }
}

// 处理项目双击
const handleItemDoubleClick = (item) => {
  if (item.type === 'folder') {
    navigateToFolder(item.id)
  } else {
    // 预览文件
    handlePreview(item)
  }
}

// 获取文件图标
const getFileIcon = (item) => {
  if (item.type === 'folder') return 'Folder'
  
  const ext = item.name.split('.').pop().toLowerCase()
  const iconMap = {
    'jpg': 'Picture',
    'jpeg': 'Picture',
    'png': 'Picture',
    'gif': 'Picture',
    'pdf': 'Document',
    'doc': 'Document',
    'docx': 'Document',
    'txt': 'Document',
    'mp4': 'VideoPlay',
    'avi': 'VideoPlay',
    'mp3': 'Headphone',
    'wav': 'Headphone'
  }
  
  return iconMap[ext] || 'Document'
}

// 获取文件类型
const getFileType = (item) => {
  if (item.type === 'folder') return '文件夹'
  
  const ext = item.name.split('.').pop().toLowerCase()
  const typeMap = {
    'jpg': '图片',
    'jpeg': '图片',
    'png': '图片',
    'gif': '图片',
    'pdf': 'PDF文档',
    'doc': 'Word文档',
    'docx': 'Word文档',
    'txt': '文本文件',
    'mp4': '视频',
    'avi': '视频',
    'mp3': '音频',
    'wav': '音频'
  }
  
  return typeMap[ext] || '文件'
}

// 格式化文件大小
const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 格式化时间
const formatTime = (time) => {
  if (!time) return ''
  const date = new Date(time)
  return date.toLocaleString()
}

// 处理命令
const handleCommand = (command, item) => {
  switch (command) {
    case 'download':
      handleDownload(item)
      break
    case 'share':
      handleShareItem(item)
      break
    case 'rename':
      handleRenameItem(item)
      break
    case 'move':
      handleMoveItem(item)
      break
    case 'copy':
      handleCopyItem(item)
      break
    case 'delete':
      handleDeleteItem(item)
      break
  }
}

// 下载文件
const handleDownload = async (item) => {
  try {
    const response = await downloadFile(item.id)
    const url = window.URL.createObjectURL(new Blob([response]))
    const link = document.createElement('a')
    link.href = url
    link.setAttribute('download', item.name)
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
  } catch (error) {
    console.error('下载失败:', error)
    ElMessage.error('下载失败')
  }
}

// 重命名
const handleRenameItem = (item) => {
  renameForm.name = item.name
  renameForm.id = item.id
  renameForm.type = item.type
  showRenameDialog.value = true
}

// 删除文件
const handleDeleteItem = (item) => {
  ElMessageBox.confirm(`确定要删除 "${item.name}" 吗？`, '确认删除', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      if (item.type === 'folder') {
        await deleteFolder(item.id)
      } else {
        await deleteFile(item.id)
      }
      ElMessage.success('删除成功')
      loadFileList()
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  })
}

// 页面加载
onMounted(() => {
  loadFileList()
  loadStorageInfo()
})
</script>

<style lang="scss" scoped>
.disk-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f5f5f5;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  background: white;
  border-bottom: 1px solid #eee;
  
  .toolbar-left {
    .el-breadcrumb {
      :deep(.el-breadcrumb__item) {
        cursor: pointer;
        
        &:hover {
          color: #409eff;
        }
      }
    }
  }
  
  .toolbar-right {
    display: flex;
    align-items: center;
  }
}

.storage-info {
  padding: 12px 16px;
  background: white;
  border-bottom: 1px solid #eee;
  display: flex;
  align-items: center;
  gap: 12px;
  
  .el-progress {
    flex: 1;
    max-width: 300px;
  }
  
  .storage-text {
    font-size: 12px;
    color: #666;
  }
}

.file-list {
  flex: 1;
  background: white;
  overflow: auto;
  
  .list-header {
    display: grid;
    grid-template-columns: 40px 1fr 100px 100px 150px 80px;
    align-items: center;
    padding: 12px 16px;
    background: #f8f9fa;
    border-bottom: 1px solid #eee;
    font-weight: 600;
    
    .header-item {
      &.name { justify-self: start; }
      &.size, &.type, &.time, &.actions { justify-self: center; }
    }
  }
  
  .file-item {
    display: grid;
    grid-template-columns: 40px 1fr 100px 100px 150px 80px;
    align-items: center;
    padding: 12px 16px;
    border-bottom: 1px solid #f0f0f0;
    cursor: pointer;
    transition: background-color 0.2s;
    
    &:hover {
      background: #f8f9fa;
    }
    
    &.selected {
      background: #e3f2fd;
    }
    
    .file-info {
      display: flex;
      align-items: center;
      gap: 8px;
      
      .file-icon {
        color: #666;
      }
      
      .file-name {
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }
    
    .file-size, .file-type, .file-time {
      justify-self: center;
      font-size: 14px;
      color: #666;
    }
    
    .file-actions {
      justify-self: center;
    }
  }
}

.batch-actions {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px 16px;
  background: #e3f2fd;
  border-top: 1px solid #eee;
}

.upload-demo {
  :deep(.el-upload-dragger) {
    width: 100%;
  }
}

@media (max-width: 768px) {
  .toolbar {
    flex-direction: column;
    gap: 12px;
    
    .toolbar-left, .toolbar-right {
      width: 100%;
    }
  }
  
  .file-list {
    .list-header, .file-item {
      grid-template-columns: 40px 1fr 80px;
      
      .file-size, .file-type, .file-time {
        display: none;
      }
    }
  }
}
</style>
